package com.gome.axwl.aoc.filter;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.anxl.sso.client.api.AccountInfo;
import com.anxl.sso.client.api.Token;
import com.anxl.sso.client.support.AnxlSsoSupport;
import com.gome.axwl.aoc.common.constants.LoginConstant;
import com.gome.axwl.aoc.service.sso.ServerGomeSsoClientService;
import com.gome.commons.core.ResultData;

/**
 * 访问权限拦截器
 *
 * @author wangjie36@gome.com.cn
 * @date 2018/2/2
 * @copyright(c) gome inc Gome Co.,LTD
 */


@Component
@Order(2)
public class AccesFilter implements Filter {
    private final static Logger logger = LoggerFactory.getLogger(AccesFilter.class);

    @Autowired
    private ServerGomeSsoClientService ssoClientService;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        request.getRequestURI().startsWith(uri)
        final String requestURI = request.getRequestURI();
        final List<String> uriExcludeList = LoginConstant.SPRING_EXCLUDE_URI.stream().
                filter(uri -> {
                    Pattern pattern = Pattern.compile(uri);
                    Matcher matcher = pattern.matcher(requestURI);
                    return uri.equals(requestURI) || matcher.matches();
                }).
                collect(Collectors.toList());

        if (uriExcludeList != null && uriExcludeList.size() < 1) {
            Token defaultToken = new Token();
            defaultToken.setText("7d0d91f1c4d74b2eadf8946929976d8f");
            defaultToken.setUid("00000316");
            defaultToken.setRefreshToken("4e4de64e2d2b4d0983a1e27b0c8fa70b");
            request.getSession().setAttribute(AnxlSsoSupport.SSO_CONTEXT, defaultToken);
            Token token = (Token) request.getSession().getAttribute(AnxlSsoSupport.SSO_CONTEXT);

            // 没有获取到token
            if (null == token || StringUtils.isEmpty(token.getText())) {
                logger.error("参数错误，没有获取到token，访问的URI：{}", requestURI);
                LoginErrorAndFlush(response);
                return;
            }
            // 获取用户信息
            if (null == request.getSession().getAttribute(LoginConstant.LOGIN_USER)) {
                final AccountInfo accountInfo = ssoClientService.getUserByLocalUserId(token.getUid(), request, response);
                if (null == accountInfo || StringUtils.isEmpty(accountInfo.getAccountNo())) {
                    logger.error("参数错误，没有获取到accountDto，访问的URI：{}，token.getUid()：{}，accountDto：{}", requestURI, token.getUid(), accountInfo.toString());
                    LoginErrorAndFlush(response);
                    return;
                }
                String accountStr = JSONObject.toJSONString(accountInfo);
                if (accountStr.length() < 5119) {            //如果长度小于5119才存入session
                    request.getSession().setAttribute(LoginConstant.LOGIN_USER, accountInfo);
                }
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 登录失败，并向响应中写失败信息
     *
     * @param response 响应
     * @author wangjie36@gome.com.cn
     * @date 2018/3/26
     */
    private void LoginErrorAndFlush(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        JSONObject responseJSONObject = (JSONObject) JSONObject.toJSON(ResultData.newResultData("1008", "没有登录或登录已过期"));
        out.print(responseJSONObject);
        out.flush();
        out.close();
    }

    @Override
    public void destroy() {

    }
}
